
#ifdef _WIN32

#define WIN_LEAN_MEAN
#include <Windows.h>

#elif _LINUX

#endif

#include <fcntl.h>
#include <io.h>

#include "BaseCode.h"
#include "LzmaLib.h"
#include "FileUtility.h"

#include "vxLzmaLib.h"


VX_LZMA_API int zipPath(const char* szPath, const char* szDstFile)
{
	CHECKF (szPath);
	CHECKF (szDstFile);

	FILE* fpZip = fopen(szDstFile, "wb+");
	if (!fpZip)
		return -1;
	
	std::vector<CMyString> setFile;
//	vxFileUtility::listFile(szPath, setFile, true);
	setFile.push_back("./test.xlsx");

	if(setFile.empty())
		return -1;

	unsigned char outProps[5] = {0};
	size_t	outPropSize = 5;
	
	while(!setFile.empty())
	{
		CMyString strFile;
		strFile = setFile.at(setFile.size()-1);
		setFile.pop_back();
		int fd = open(strFile.c_str(), _O_BINARY|_O_RDONLY);
		if (fd<0)
		{
			BC_LOGERROR("lzmb compress open File[%s] failed!", strFile.c_str());
			continue;
		}

		unsigned long uFileLen = filelength(fd);
		unsigned char* pEncCode = new unsigned char[uFileLen*10];
		unsigned char* pData = new unsigned char[uFileLen];
		size_t nReadData = 0;
		size_t nEncData = uFileLen*10;

		nReadData = read(fd, pData, uFileLen);
		if(nReadData > 0)
		{
			int nRet = LzmaCompress(pEncCode, &nEncData, pData, nReadData, outProps, &outPropSize, 5, 1<<24, 3, 0, 2, 32, 2);
			if (nRet != SZ_OK)
			{
				printf("%u\n", nRet);
			}

			fwrite(pEncCode, nEncData, 1, fpZip);
		}

		char szFileLen[6] = {0};
		//::itoa(uFileLen, szFileLen, 10);
		fwrite(&uFileLen, 6, 1, fpZip);

		delete []pEncCode;
		delete []pData;

		close(fd);
	}

	fclose(fpZip);
	return SZ_OK;
}

VX_LZMA_API	int unzipFile(const char* szZipFile, const char* szDstPath)
{
	FILE* fp = fopen(szDstPath, "wb+");
	if (!fp)
		return -1;

	unsigned char outProps[5] = {93,0,0,0,1};
	size_t	outPropSize = 5;

	int fd = open(szZipFile, _O_BINARY|_O_RDONLY);
	if (fd<0)
		return -1;

	unsigned long uFileLen = filelength(fd);
	unsigned char* pDecCode = new unsigned char[uFileLen*100];
	unsigned char* pData = new unsigned char[uFileLen+10];
	size_t nReadData = 0;
	size_t nDecData = uFileLen*100;

	nReadData = read(fd, pData, uFileLen);
	if (nReadData > 0)
	{
		{
//			nReadData+=10;
			int nRet = LzmaUncompress(pDecCode, &nDecData, pData, &nReadData, outProps, outPropSize);
			if (nRet != SZ_OK)
			{
				printf("%u\n", nRet);
			}
			else
				fwrite(pDecCode, nDecData, 1, fp);
		}
	}

	delete []pData;
	delete []pDecCode;

	close(fd);

	fclose(fp);

	return SZ_OK;
}